#include <QCoreApplication>

#include <QtNetwork>
#include <QDebug>

#include "ThingpleTcpServerHandler.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QCoreApplication::setOrganizationName("AlienGen");
    QCoreApplication::setOrganizationDomain("aliengen.com");
    QCoreApplication::setApplicationName("ThingpleFillingLineServer");

    QSettings settings(QCoreApplication::applicationDirPath() + "/settings.ini", QSettings::IniFormat);

    int port = settings.value("FillingLineServer/port", 42000).toInt();
    QString serialPort = settings.value("FillingLineServer/serial", "/dev/ttyAMA0").toString();

    unsigned char isActive[8]= {0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00};
    unsigned char active[8] = {0};


    AlienGenSerialLine ttl(serialPort.toStdString());
    int serialFd = ttl.open();

    if(serialFd < 0)
    {
        qDebug() << "Serial line not available!" << serialPort;
        return 1;
    }
    qDebug() << "Serial line is open !";

    int ret;
    ret = write(serialFd,isActive,8);
    if(ret < 0)
    {
        qDebug()<< "write serial failed !";
    }
    qDebug()<< "write" << ret << "bytes !";

    usleep(2000);

    ret = read(serialFd,active,8);
    if(ret < 0)
    {
        qDebug()<< "read serial failed !";
    }
    qDebug()<< "read" << ret << "bytes !";

    if(active[4] != 0)
    {
        qDebug() << "MAC is not active !";
        return 1;
    }

    qDebug() << "Serial line available" << serialPort;

    ThingpleTcpServerHandler h(port, serialPort);
    h.startServer();

    return a.exec();
}
